package com.xiaoyu.lanling.feature.fate

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.event.fate.MainFatePreferenceUpdateEvent
import com.xiaoyu.lanling.event.location.AddressEvent
import com.xiaoyu.lanling.event.user.UserSetProfileEvent
import com.xiaoyu.lanling.feature.board.data.BoardDataCreator
import com.xiaoyu.lanling.feature.fate.controller.MainFateNearbyUserListController
import com.xiaoyu.lanling.feature.fate.data.MainFateNearbyUserListData
import com.xiaoyu.lanling.feature.user.data.UserInfoData
import com.xiaoyu.lanling.view.OnShowFragment
import kotlinx.android.synthetic.main.fragment_main_fate_nearby.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainFateNearbyFragment : OnShowFragment() {

    private val requestTag = Any()
    private var listController: MainFateNearbyUserListController? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return layoutInflater.inflate(R.layout.fragment_main_fate_nearby, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        initEvent()
        initData()
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: MainFatePreferenceUpdateEvent) {
                loadFirstPageData()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: AddressEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                UserInfoData.setLocation(requestTag, event.province, event.city, event.county)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: UserSetProfileEvent) {
                if (event.isFailed) {
                    return
                }
                loadFirstPageData()
            }
        })
    }

    private fun initData() {
        val listData = MainFateNearbyUserListData()
        context?.let {
            listController = MainFateNearbyUserListController.create(it, listData, swipe_refresh_layout, recyclerview)
        }
        requestBoardTop3()
    }

    private fun requestBoardTop3() {
        BoardDataCreator.getBoardTop3(requestTag)
    }

    private fun loadFirstPageData() {
        listController?.loadFirstPageData()
    }
}